package com.mlink.ai.chat.ui.activity

import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import com.adsdk.android.ads.consent.OxAdSdkConsentManager
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.Purchase
import com.icekrvams.billing.Billing
import com.icekrvams.billing.listeners.BillingDataResponseListener
import com.mlink.ai.chat.AiChatApplication
import com.mlink.ai.chat.ads.chatRewardCache
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.assistant.robot.databinding.ActivityMainBinding
import com.mlink.ai.chat.constants.KEY_IS_BILLING_SHOWED
import com.mlink.ai.chat.constants.isFirstOpenApp
import com.mlink.ai.chat.ui.fragment.ChatFragment
import com.mlink.ai.chat.ui.fragment.ExploreFragment
import com.mlink.ai.chat.ui.fragment.SettingFragment
import com.mlink.ai.chat.ui.view.BottomNavigationTab
import com.mlink.ai.chat.ui.view.KEY_SELECTED_TAB
import com.mlink.ai.chat.utils.*
import com.tencent.mmkv.MMKV

class MainActivity : BaseActivity<ActivityMainBinding>() {

    private val appViewModel = AiChatApplication.app.appViewModel

    private var exploreFragment: ExploreFragment? = null
    private var chatFragment: ChatFragment? = null
    private var settingFragment : SettingFragment? = null

    private lateinit var notificationUtils: NotificationUtils


    private val billingActivityResultLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            showDialogs()
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        notificationUtils = NotificationUtils(this)

        // 连接 BillingClient, 页面 onDestroy() 会自动断开 BillingClient 连接。
        Billing.mainEntrance(this)

        Billing.addBillingDataResponseListener(
            object : BillingDataResponseListener {
                override fun onQueryPurchasesResponse(
                    billingResult: BillingResult, purchasesList: List<Purchase>
                ) {
                    // 查询已拥有商品信息结果回调。
                    if (purchasesList.isEmpty()) {
                        appViewModel.setSubscribed(false)
                        return
                    }
                    val purchase = purchasesList[0]
                    if (purchase.products.firstOrNull()
                            .isNullOrEmpty() || purchase.orderId.isEmpty() ||
                        purchase.purchaseToken.isEmpty()
                    ) {
                        appViewModel.setSubscribed(false)
                        return
                    }
                    val pair = Pair<String, Purchase>(purchase.products[0], purchase)
                    appViewModel.purchaseLiveData.value = pair
                    appViewModel.doSubscribe(
                        purchase.products[0], purchase.orderId, purchase.purchaseToken
                    )
                }
            }, this
        ) // 推荐传入 LifecycleOwner 参数，以便其生命周期结束时，listener 得以被自动移除。

        if (savedInstanceState != null) {
            exploreFragment = supportFragmentManager.getFragment(savedInstanceState,
                KEY_EXPLORE_FRAGMENT) as? ExploreFragment
            chatFragment = supportFragmentManager.getFragment(savedInstanceState,
                KEY_CHAT_FRAGMENT) as? ChatFragment
            settingFragment =supportFragmentManager.getFragment(savedInstanceState,
            KEY_RECENT_FRAGMENT) as? SettingFragment
        }

        when (MMKV.defaultMMKV().decodeInt(KEY_SELECTED_TAB, 1)) {
            0 -> binding.bottomNavigation.performClickTab(BottomNavigationTab.TAB_EXPLORE)
            1 -> binding.bottomNavigation.performClickTab(BottomNavigationTab.TAB_CHAT)
            2 -> binding.bottomNavigation.performClickTab(BottomNavigationTab.TAB_RECENTS)
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        exploreFragment?.let {
            supportFragmentManager.putFragment(
                outState,
                KEY_EXPLORE_FRAGMENT,
                it
            )
        }
        chatFragment?.let { supportFragmentManager.putFragment(outState, KEY_CHAT_FRAGMENT, it) }
        settingFragment?.let {
            supportFragmentManager.putFragment(
                outState,
                KEY_RECENT_FRAGMENT,
                it
            )
        }
        super.onSaveInstanceState(outState)
    }

    private fun showExploreFragment() {
        if (exploreFragment == null) {
            exploreFragment = ExploreFragment.newInstance()
            supportFragmentManager.beginTransaction()
                .add(R.id.fl_container, exploreFragment!!)
                .commit()
        } else {
            supportFragmentManager.beginTransaction().show(exploreFragment!!).commit()
        }
    }
    
    private fun hideExploreFragment() {
        exploreFragment?.let {
            supportFragmentManager.beginTransaction().hide(it).commit()
        }
    }

    private fun showChatFragment() {
        if (chatFragment == null) {
            chatFragment = ChatFragment()
            supportFragmentManager.beginTransaction()
                .add(R.id.fl_container, chatFragment!!)
                .commit()
        } else {
            supportFragmentManager.beginTransaction().show(chatFragment!!).commit()
        }
    }

    private fun hideChatFragment() {
        chatFragment?.let {
            supportFragmentManager.beginTransaction().hide(it).commit()
        }
    }

    private fun showRecentFragment() {
        if (settingFragment == null) {
            settingFragment = SettingFragment()
            supportFragmentManager.beginTransaction()
                .add(R.id.fl_container, settingFragment!!)
                .commit()
        } else {
            supportFragmentManager.beginTransaction().show(settingFragment!!).commit()
        }
    }

    private fun hideRecentFragment() {
        settingFragment?.let {
            supportFragmentManager.beginTransaction().hide(it).commit()
        }
    }

    override fun getViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initViews() {

        appViewModel.getSubscribeLiveData().observe(this) {
            if (!it) {
                if (!MMKV.defaultMMKV().decodeBool(KEY_IS_BILLING_SHOWED, false)) {
                    MMKV.defaultMMKV().encode(KEY_IS_BILLING_SHOWED, true)
                    val intent = Intent(this, BillingActivity::class.java).apply {
                        putExtra(
                            BillingActivity.KEY_VIP_TYPE, if (isFirstOpenApp) {
                                AnalyticsParams.FIRST_OPEN_APP
                            } else {
                                AnalyticsParams.OPEN_APP
                            }
                        )
                    }
                    billingActivityResultLauncher.launch(intent)
                } else {
                    showDialogs()
                }
                // chat RV 广告预加载
                chatRewardCache.initRewardAdCache(this)
            } else {
                showDialogs()
            }
            isFirstOpenApp = false
        }

        binding.bottomNavigation.bottomTabClickListener = {
            // do nothing now
            when (it) {
                BottomNavigationTab.TAB_EXPLORE -> {
                    MMKV.defaultMMKV().encode(KEY_SELECTED_TAB,0)
                    AnalyticsEvents.AC_NAVBAR_BUTTON_CLICK.logEvent(
                        Bundle().apply { putString(AnalyticsParams.KEY_TITLE,AnalyticsParams.EXPLORE) }
                    )
                    showExploreFragment()
                    hideChatFragment()
                    hideRecentFragment()
                }
                BottomNavigationTab.TAB_CHAT -> {
                    MMKV.defaultMMKV().encode(KEY_SELECTED_TAB,1)
                    AnalyticsEvents.AC_NAVBAR_BUTTON_CLICK.logEvent(
                        Bundle().apply { putString(AnalyticsParams.KEY_TITLE,AnalyticsParams.CHAT) }
                    )
                    showChatFragment()
                    hideExploreFragment()
                    hideRecentFragment()
                }
                BottomNavigationTab.TAB_RECENTS -> {
                    MMKV.defaultMMKV().encode(KEY_SELECTED_TAB,2)
                    AnalyticsEvents.AC_NAVBAR_BUTTON_CLICK.logEvent(
                        Bundle().apply { putString(AnalyticsParams.KEY_TITLE,AnalyticsParams.RECENTS) }
                    )
                    showRecentFragment()
                    hideExploreFragment()
                    hideChatFragment()
                }
            }
        }

        binding.settingIv.setOnClickListener {
            startActivity(Intent(this, SettingsActivity::class.java))
        }

    }

    private fun showDialogs() {
        showGDPRSettings()
        if (this::notificationUtils.isInitialized) {
            notificationUtils.askNotificationPermission(this)
        }
        UpgradeUtils.checkRemoteVersion(this)
    }

    private fun showGDPRSettings() {
        val oxAdSdkConsentManager = OxAdSdkConsentManager.getInstance(this)
        if (oxAdSdkConsentManager.isSupportedGDPR) {
            oxAdSdkConsentManager.showPrivacyDialog(this)
        }
    }

    companion object {
        private const val KEY_EXPLORE_FRAGMENT = "key_explore_fragment"
        private const val KEY_CHAT_FRAGMENT = "key_chat_fragment"
        private const val KEY_RECENT_FRAGMENT = "key_recent_fragment"
    }

}